import axios from 'axios';
import useUserStore from '@/store/modules/userStore'
import type { AxiosInstance ,InternalAxiosRequestConfig,AxiosResponse} from 'axios';
import { Message } from '@arco-design/web-vue';

type HttpConfig = {
  serviceName: string; 
}

export class Http {
  baseUrl = import.meta.env.VITE_API_URL;
  timeout = 30000;
  axiosInstance:AxiosInstance;
  constructor({ serviceName }:HttpConfig) {
    this.axiosInstance = axios.create({
      baseURL: this.baseUrl + serviceName,
      timeout: this.timeout,
    });
    this.axiosInstance.interceptors.request.use((service) => {
      service = this.requestInterceptors(service);
      return service;
    });
    this.axiosInstance.interceptors.response.use(
      (service) => {
        service = this.responceInterceptors(service);
        return service;
      },
      (error) => {
        this.responceInterceptorsError(error);
        return Promise.reject(error);
      }
    );
  }

  //请求拦截
  requestInterceptors(service:InternalAxiosRequestConfig) {
    var userStore = useUserStore();
    var method = service.method;
    var data:any = {}
    service.headers["Authorization"] = userStore.token||"";
    if (method == 'get') {
      data = { ...service.params }
      // userStore.token && (data['token'] = userStore.token);

    } else if (method == 'post') {

      if (service.data instanceof FormData) {
        data = service.data
        // data.append('token', userStore.token)

      } else {
        data = { ...service.data }
        // userStore.token && (data['token'] = userStore.token);
      }

    }
    method == 'get' ? (service.params = data) : (service.data = data);
    return service;
  }

  // 响应成功拦截
  responceInterceptors(service:AxiosResponse) {
    if(service.data['code'] == 401){
      Message.warning({
        content:'token 失效或无效，请退出并重新登录！',
        id:'404:token-error' //加唯一id 确保同一id提示只显示一次
      })
    }

    service.data['code'] || (service.data['code'] = service.data['Code'])
    return service.data;
  }

  //响应错误/失败拦截
  responceInterceptorsError(error:any) {
    var errorStatusText:any = {
      500: () => {
        console.error('服务器异常，状态 ' + error?.response?.status);
      },
      503: () => {
        console.error('服务器异常，状态 ' + error?.response?.status);
      },
      404: () => {
        console.error('请求失败，状态 404');
      },
      403: () => {
        console.error('token失败');
      },
    };

    if (!error.isAxiosError) {
      console.error('网络异常，请检查网络');
    } else {
      //存在状态码的情况
      if (error?.response?.status) {
        errorStatusText[error.response?.status]?.();
      }
      //不存在状态码的情况
      else {
        console.error('网络连接失败，请重试');
      }
    }
  }
}

//刷新token
function refreshToken() { }



export default new Http({ serviceName: "" }).axiosInstance; 

